package com.css.zfzx.data.primary.fxEconomicLossEvaluationMapPG.service.impl;

import ch.ethz.ssh2.Connection;
import com.css.zfzx.data.common.Constant;
import com.css.zfzx.data.common.Enum;
import com.css.zfzx.data.common.ProvinceCityAreaUtil;
import com.css.zfzx.data.common.RemoteCommandUtil;
import com.css.zfzx.data.primary.fxEconomicLossEvaluationMapPG.repository.entity.FxEconomicLossEvaluationMapPGEntity;
import com.css.zfzx.data.primary.fxEconomicLossEvaluationMapPG.repository.FxEconomicLossEvaluationMapPGNativeRepository;
import com.css.zfzx.data.primary.fxEconomicLossEvaluationMapPG.service.FxEconomicLossEvaluationMapPGService;
import com.css.zfzx.data.primary.sysAttachmentInfo.repository.SysAttachmentInfoRepository;
import com.css.zfzx.data.thirdary.fjgReconciliation.repository.FjgReconciliationNativeRepository;
import com.css.zfzx.data.thirdary.fjgReconciliation.repository.FjgReconciliationRepository;
import com.css.zfzx.data.thirdary.fjgReconciliation.repository.entity.SjtgfFjghshDzSjdzbEntity;
import com.css.zfzx.data.thirdary.ftpReconciliation.repository.FtpReconciliationRepository;
import com.css.zfzx.data.thirdary.ftpReconciliation.repository.entity.SjtgfFjghshDzSgysjbEntity;
import com.css.zfzx.data.thirdary.jgReconciliation.service.ReconciliationService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
@Slf4j
@Data
public class FxEconomicLossEvaluationMapPGServiceImpl implements FxEconomicLossEvaluationMapPGService {

    /**
     * linux地址
     **/
    //@Value("${linux.linux-ip}")
    public String linuxAddress = "10.7.208.209";
    /**
     * linux用户名
     **/
    //@Value("${linux.linux-user}")
    private String linuxUsername = "lhl";
    /**
     * linux密码
     **/
    //@Value("${linux.linux-pwd}")
    private String linuxPassword = "107208209";

    private final FxEconomicLossEvaluationMapPGNativeRepository fxEconomicLossEvaluationMapPGNativeRepository;
    private final ReconciliationService reconciliationService;
    private final SysAttachmentInfoRepository sysAttachmentInfoRepository;
    private final FtpReconciliationRepository ftpReconciliationRepository;
    private final FjgReconciliationRepository fjgReconciliationRepository;
    private final FjgReconciliationNativeRepository fjgReconciliationNativeRepository;

    @Autowired
    public FxEconomicLossEvaluationMapPGServiceImpl(FxEconomicLossEvaluationMapPGNativeRepository fxEconomicLossEvaluationMapPGNativeRepository, ReconciliationService reconciliationService, SysAttachmentInfoRepository sysAttachmentInfoRepository, FtpReconciliationRepository ftpReconciliationRepository, FjgReconciliationRepository fjgReconciliationRepository, FjgReconciliationNativeRepository fjgReconciliationNativeRepository) {
        this.fxEconomicLossEvaluationMapPGNativeRepository = fxEconomicLossEvaluationMapPGNativeRepository;
        this.reconciliationService = reconciliationService;
        this.sysAttachmentInfoRepository = sysAttachmentInfoRepository;
        this.ftpReconciliationRepository = ftpReconciliationRepository;
        this.fjgReconciliationRepository = fjgReconciliationRepository;
        this.fjgReconciliationNativeRepository = fjgReconciliationNativeRepository;
    }

    @Override
    public void findData(int flag) {
        Map<String, String> errorMap = new HashMap<>();
        List<FxEconomicLossEvaluationMapPGEntity> FxEconomicLossEvaluationMapPGEntities = null;
        if (flag == 1) {//查询新增数据
            LocalDateTime createTime = ftpReconciliationRepository.findCreateTime("%"+Constant.SJDXXHMC_E+"%");
            FxEconomicLossEvaluationMapPGEntities = fxEconomicLossEvaluationMapPGNativeRepository.findFxEconomicLossEvaluationMapPGCreate(createTime);
        } else if (flag == 2) {//查询修改数据
            LocalDateTime updateTime = ftpReconciliationRepository.findUpdateTime("%"+Constant.SJDXXHMC_E+"%");
            FxEconomicLossEvaluationMapPGEntities = fxEconomicLossEvaluationMapPGNativeRepository.findFxEconomicLossEvaluationMapPGUpdate(updateTime);
        }
        if (FxEconomicLossEvaluationMapPGEntities.size() == 0) {
            if (flag == 1) {//查询新增数据
                System.out.println("fx_economic_loss_evaluation_map:时间" + new Date() + ",添加查询了数据：" + FxEconomicLossEvaluationMapPGEntities.size() + " 条");
            } else if (flag == 2) {//查询修改数据
                System.out.println("fx_economic_loss_evaluation_map:时间" + new Date() + ",修改查询了数据：" + FxEconomicLossEvaluationMapPGEntities.size() + " 条");
            }
            return;
        }
        String filePath = Constant.FTP_PATH2;
        List<SjtgfFjghshDzSgysjbEntity> saveList = new ArrayList<>();
        Connection conn = RemoteCommandUtil.login(Enum.SERVER_1.getAddress(), Enum.SERVER_1.getUsername(), Enum.SERVER_1.getPassword());
        Connection conn2 = RemoteCommandUtil.login(Enum.SERVER_2.getAddress(), Enum.SERVER_2.getUsername(),
                Enum.SERVER_2.getPassword());
        StringBuilder dataIds = new StringBuilder();//文件Id
        StringBuilder wjmcs = new StringBuilder();//存储文件名
        StringBuilder wjljs = new StringBuilder();//存储文件路径
        String[] wjlxStrs = {".tfw", ".tif", ".tif.aux.xml"};
        for (FxEconomicLossEvaluationMapPGEntity entity : FxEconomicLossEvaluationMapPGEntities) {
            String code = ProvinceCityAreaUtil.getCode(entity.getProvince(), entity.getCity(), entity.getArea());
            if (code == null) {
                throw new RuntimeException("province:{}" + entity.getProvince() + "city:{}" + entity.getCity() +
                        "area:{}" + entity.getArea() + "的区划编码获取失败，请检查后再导入");
            }
            String wjlj = "";//存储文件路径
            StringBuilder zykjdx = new StringBuilder();//存储文件大小
            String result = "";
            dataIds.append(",").append(entity.getUuid());
            String affiliatedFileName = entity.getAffiliatedFileName();
            wjmcs.append(",").append(affiliatedFileName + ".tif");
            boolean isNa = false;
            for (String str : wjlxStrs) {
                String cmd = "find /data/fujian/SHP/ -name '" + affiliatedFileName + "'" + str;
                result = RemoteCommandUtil.execmd(conn, cmd);
                if (StringUtils.isEmpty(result) || result.length() <= 0) {
                    continue;
                }
                isNa = true;
                result = result.substring(0, result.indexOf("\n"));
                wjlj="/economic_loss/" + code;
                cmd = "du -b '" + result +"'";
                String linuxPath = result;
                result = RemoteCommandUtil.execmd(conn, cmd);
                double total = Double.parseDouble(result.substring(0, result.indexOf("/")));
                total = total / 1024 / 1024;
                if (total > 1) {
                    total = total / 1024;
                }
                zykjdx.append(",").append(total);//得到文件占用内存的大小
                String cmd2 = "mkdir -p " + filePath + code;
                RemoteCommandUtil.execmd(conn2, cmd2);
                cmd = "scp '" + linuxPath + "' " + Enum.SERVER_2.getUsername() + "@" + Enum.SERVER_2.getAddress() + ":"
                        + filePath + code + "/";
                RemoteCommandUtil.execmd(conn, cmd);
            }
            if (isNa) {
                SjtgfFjghshDzSgysjbEntity sjtgfFjghshDzSgysjbEntity = new SjtgfFjghshDzSgysjbEntity();
                sjtgfFjghshDzSgysjbEntity.setDataid(entity.getUuid());
                sjtgfFjghshDzSgysjbEntity.setWjmc(affiliatedFileName + ".tif");
                sjtgfFjghshDzSgysjbEntity.setWjlx(".tif");
                wjljs.append(",").append(wjlj);
                sjtgfFjghshDzSgysjbEntity.setWjlj(wjlj);
                sjtgfFjghshDzSgysjbEntity.setCreatetime(entity.getCreateTime());
                sjtgfFjghshDzSgysjbEntity.setUpdatetime(ftpReconciliationRepository.getTimeNow());
                switch (entity.getEarthquakeRisk()){
                    case "0":sjtgfFjghshDzSgysjbEntity.setSjdxxhmc(Constant.SJDXXHMC_E1);break;
                    case "1":sjtgfFjghshDzSgysjbEntity.setSjdxxhmc(Constant.SJDXXHMC_E2);break;
                    case "2":sjtgfFjghshDzSgysjbEntity.setSjdxxhmc(Constant.SJDXXHMC_E3);break;
                    case "3":sjtgfFjghshDzSgysjbEntity.setSjdxxhmc(Constant.SJDXXHMC_E4);break;
                }
                sjtgfFjghshDzSgysjbEntity.setCglx(Constant.CGLX_TJ);
                sjtgfFjghshDzSgysjbEntity.setSjl("");
                sjtgfFjghshDzSgysjbEntity.setSjzysm(entity.getAffiliatedFileName());
                sjtgfFjghshDzSgysjbEntity.setZykjdx(zykjdx.substring(1));
                //sjtgfFjghshDzSgysjbEntity.setZykjdx("0");
                sjtgfFjghshDzSgysjbEntity.setSshy(Constant.SSHY_DZ);
                //根据名称获取行政编码
                if (!StringUtils.isEmpty(entity.getProvince()) && StringUtils.isEmpty(entity.getCity())) {
                    sjtgfFjghshDzSgysjbEntity.setXzqha(code.substring(0, 2) + "0000");
                }
                if (!StringUtils.isEmpty(entity.getCity()) && StringUtils.isEmpty(entity.getArea())) {
                    sjtgfFjghshDzSgysjbEntity.setXzqha(code.substring(0, 2) + "0000");
                    sjtgfFjghshDzSgysjbEntity.setXzqhb(code.substring(0, 4) + "00");
                }
                if (!StringUtils.isEmpty(entity.getArea())) {
                    sjtgfFjghshDzSgysjbEntity.setXzqha(code.substring(0, 2) + "0000");
                    sjtgfFjghshDzSgysjbEntity.setXzqhb(code.substring(0, 4) + "00");
                    sjtgfFjghshDzSgysjbEntity.setXzqhc(code);
                }
                if ("1".equals(entity.getIsValid())) {
                    if (entity.getUpdateTime() == null) {
                        sjtgfFjghshDzSgysjbEntity.setSjzt(Constant.SJZT_I);
                    } else {
                        sjtgfFjghshDzSgysjbEntity.setSjzt(Constant.SJZT_U);
                    }
                } else if ("0".equals(entity.getIsValid())) {
                    sjtgfFjghshDzSgysjbEntity.setSjzt(Constant.SJZT_D);
                }
                sjtgfFjghshDzSgysjbEntity.setShlczt(Constant.SHLCZT_ZZSH);
                sjtgfFjghshDzSgysjbEntity.setShzt(Constant.SHZT_TG);
                saveList.add(sjtgfFjghshDzSgysjbEntity);
            } else {
                errorMap.put(entity.getUuid(), affiliatedFileName + " 不存在！");
            }
        }
        RemoteCommandUtil.closeConn(conn);
        RemoteCommandUtil.closeConn(conn2);
        long startIn = System.currentTimeMillis();
        ftpReconciliationRepository.saveAll(saveList);
        long endIn = System.currentTimeMillis();
        log.error(errorMap.toString());
        System.out.println("fx_economic_loss_evaluation_map:插入数据：" + saveList.size() + " 条,用时  " + (endIn - startIn));
        SjtgfFjghshDzSjdzbEntity sjtgfFjghshDzSjdzbEntity = new SjtgfFjghshDzSjdzbEntity();
        sjtgfFjghshDzSjdzbEntity.setDataid(dataIds.substring(1));
        sjtgfFjghshDzSjdzbEntity.setBmc("fx_economic_loss_evaluation_map");
        sjtgfFjghshDzSjdzbEntity.setLch(1);
        sjtgfFjghshDzSjdzbEntity.setWjmc(wjmcs.substring(1));
        sjtgfFjghshDzSjdzbEntity.setWjlj(wjljs.substring(1));
        sjtgfFjghshDzSjdzbEntity.setSjzw(null);
        sjtgfFjghshDzSjdzbEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
        fjgReconciliationRepository.save(sjtgfFjghshDzSjdzbEntity);
    }
}
